package com.xc58.highreactor.util;

import com.xc58.highreactor.exception.ByteArrayCastToObjectException;

public class ByteUtil {
	public static byte[] getByteFormShort(short raw) {
        byte[] result = new byte[2];
        result[0] = (byte) raw;
        result[1] = (byte) (raw >> 8);
        return result;
    }
	
	public static short toShort(byte[] raw){
		if(raw.length < 2){
			throw new ByteArrayCastToObjectException(2, raw.length);
		}
		short result = 0;
		//bit caculete's result is int, so add & 0xFF,otherwise will display nagetive
		return (short) (((result | raw[1]) << 8) | (raw[0] & 0xFF)); 
	}
	
	public static byte[] getByteFormInt(int raw) {
		byte[] result = new byte[4];
        result[0] = (byte) raw;
        result[1] = (byte) (raw >> 8);
        result[2] = (byte) (raw >> 16);
        result[3] = (byte) (raw >> 24);
        return result;
    }
	
	public static int toInt(byte[] raw){
		if(raw.length < 4){
			throw new ByteArrayCastToObjectException(4, raw.length);
		}
		int result = 0;
		//bit caculete's result is int, so add & 0xFF,otherwise will display nagetive
		return result | ((raw[3] & 0xFF) << 24) | ((raw[2] & 0xFF) << 16) | ((raw[1] & 0xFF) << 8) | (raw[0] & 0xFF); 
	}
	
	public static byte[] getByteFormLong(long raw) {
		byte[] result = new byte[8];
        result[0] = (byte) raw;
        result[1] = (byte) (raw >> 8);
        result[2] = (byte) (raw >> 16);
        result[3] = (byte) (raw >> 24);
        result[4] = (byte) (raw >> 32);
        result[5] = (byte) (raw >> 40);
        result[6] = (byte) (raw >> 48);
        result[7] = (byte) (raw >> 56);
        return result;
    }
	
	public static long toLong(byte[] raw){
		if(raw.length < 8){
			throw new ByteArrayCastToObjectException(8, raw.length);
		}
		long result = 0;
		//bit caculete's result is int, so add & 0xFF,otherwise will display nagetive
		return result | ((raw[7] & 0xFFL) << 56) | ((raw[6] & 0xFFL) << 48) | ((raw[5] & 0xFFL) << 40) | ((raw[4] & 0xFFL) << 32) 
				| ((raw[3] & 0xFFL) << 24) | ((raw[2] & 0xFF) << 16) | ((raw[1] & 0xFF) << 8) | (raw[0] & 0xFF); 
	}
}
